package com.yic.module.device.service.faulthandle;

import com.yic.framework.security.core.util.SecurityFrameworkUtils;
import com.yic.module.device.service.fault.FaultService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.yic.module.device.controller.admin.faulthandle.vo.*;
import com.yic.module.device.dal.dataobject.faulthandle.FaultHandleDO;
import com.yic.framework.common.pojo.PageResult;

import com.yic.module.device.convert.faulthandle.FaultHandleConvert;
import com.yic.module.device.dal.mysql.faulthandle.FaultHandleMapper;

import static com.yic.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yic.module.device.enums.ErrorCodeConstants.*;

/**
 * 设备报修处理 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class FaultHandleServiceImpl implements FaultHandleService {

    @Resource
    private FaultHandleMapper faultHandleMapper;
    @Resource
    private FaultService faultService;

    @Override
    @Transactional
    public Long createFaultHandle(FaultHandleCreateReqVO createReqVO) {
        // 插入
        FaultHandleDO faultHandle = FaultHandleConvert.INSTANCE.convert(createReqVO);
        faultHandle.setHandleUser(SecurityFrameworkUtils.getLoginUserId());
        faultHandleMapper.insert(faultHandle);
        faultService.handleFault(faultHandle.getFaultId());
        // 返回
        return faultHandle.getId();
    }

    @Override
    public void updateFaultHandle(FaultHandleUpdateReqVO updateReqVO) {
        // 校验存在
        validateFaultHandleExists(updateReqVO.getId());
        // 更新
        FaultHandleDO updateObj = FaultHandleConvert.INSTANCE.convert(updateReqVO);
        faultHandleMapper.updateById(updateObj);
    }

    @Override
    public void deleteFaultHandle(Long id) {
        // 校验存在
        validateFaultHandleExists(id);
        // 删除
        faultHandleMapper.deleteById(id);
    }

    private void validateFaultHandleExists(Long id) {
        if (faultHandleMapper.selectById(id) == null) {
            throw exception(FAULT_HANDLE_NOT_EXISTS);
        }
    }

    @Override
    public FaultHandleDO getFaultHandle(Long id) {
        return faultHandleMapper.selectById(id);
    }

    @Override
    public List<FaultHandleDO> getFaultHandleList(Collection<Long> ids) {
        return faultHandleMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<FaultHandleDO> getFaultHandlePage(FaultHandlePageReqVO pageReqVO) {
        return faultHandleMapper.selectPage(pageReqVO);
    }

    @Override
    public List<FaultHandleDO> getFaultHandleList(FaultHandleExportReqVO exportReqVO) {
        return faultHandleMapper.selectList(exportReqVO);
    }

}
